package com.javaee.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        // 从session中获取用户信息
        Object user = request.getSession().getAttribute("user");

        if (user == null) {
            // 用户未登录，重定向到登录页面
            response.sendRedirect("/login");
            return false; // 返回false，中断请求的处理
        }

        // 用户已登录，继续处理请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // 请求处理之后进行调用，但在视图被渲染之前
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // 在整个请求结束之后调用，也就是在DispatcherServlet渲染了视图执行
    }
}
